package com.link510.aitools.core.helper;

import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;

public class ByteHelper {


    private static final String TAG = ByteHelper.class.getSimpleName();

    /**
     * 字节32位转8字节
     *
     * @param arg
     * @return
     */
    public static char[] data32todata8(long[] arg) {
        int len = arg.length * 4;
        char[] rs = new char[len];
        int m = 0, n = 0;
        while (n < arg.length) {
            rs[m++] = getUint8((char) arg[n]);
            rs[m++] = getUint8((char) (arg[n] >> 8));
            rs[m++] = getUint8((char) (arg[n] >> 16));
            rs[m++] = getUint8((char) (arg[n] >> 24));
            n++;
        }
        return rs;
    }

    /**
     * 8位转32位
     *
     * @param bytes
     * @return
     */
    public static long[] data8todata32(char[] bytes) {
        int len = bytes.length % 4 == 0 ? bytes.length / 4 : bytes.length / 4 + 1;
        long[] rs = new long[len];
        int n = 0;
        while (n < (bytes.length)) {
            switch (n % 4) {
                case 0:
                    rs[n / 4] = getUint32(bytes[n]);
                    break;
                case 1:
                    rs[n / 4] = rs[n / 4] + getUint32(bytes[n] << 8);
                    break;
                case 2:
                    rs[n / 4] = rs[n / 4] + getUint32(bytes[n] << 16);
                    break;
                case 3:
                    rs[n / 4] = rs[n / 4] + getUint32(bytes[n] << 24);
                    break;
                default:
            }
            n++;
        }
        return rs;
    }


    /**
     * 获取8位数字节
     *
     * @param s
     * @return
     */
    public static char getUint8(char s) {
        return (char) (s & 0x00ff);
    }

    /**
     * 获取32位的字节
     *
     * @param l
     * @return
     */
    public static long getUint32(long l) {
        return l & 0x00000000ffffffffL;
    }


    /**
     * hex转字符串
     *
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {

        if (s == null || "".equals(s)) {
            return null;
        }
        s = s.replace(" ", "");
        char[] buf = new char[s.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            try {
                buf[i] = (char) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return String.valueOf(buf);
    }

    /**
     * hex转字节
     *
     * @param s
     * @return
     */
    public static byte[] hexStringToByte(String s) {

        //System.out.println(s);

        if (s == null || "".equals(s)) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] buf = new byte[s.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            try {
                buf[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return buf;
    }

    /**
     * 字符串转hex字符串
     *
     * @param s 原串
     * @return
     */
    public static String stringToHexString(String s) {
        char[] sss = s.toCharArray();
        StringBuilder result = new StringBuilder();
        for (char ss : sss) {
            result.append(toHexString(ss));
        }
        return result.toString().toUpperCase();
    }


    /**
     * 二进制自动补0
     *
     * @param c 源参数
     * @return
     */
    public static String toHexString(char c) {
        String str = Integer.toHexString(c);
        if (str.length() < 2) {
            str = "0" + str;
        }
        return str;
    }

    public static void main(String[] args) {
        System.out.println(encode("中文"));
        System.out.println(decode(encode("中文")));

        String s = stringToHexString("yZ$$ºç\u008Ba\u0097oµÀ\u0015Ò¨2îùOLÒû=rTlÐW\u0091ý\u0094´o!åj`×ß³hëæ1ì+\u0084Y\u0002ý\u0015èÀÐþu}\u0093ÓZLfn\u0018\u008BÄPSÿ~®ÿt\u008C¬ù\bCÖ¤¯u\u0082u\u0011Ï\u009A®Õ\u0097\u0086b");

        System.out.println(s);

    }

    /*
     * 16进制数字字符集
     */
    private static String hexString = "0123456789ABCDEF";

    /*
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encode(String str) {
        //根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        //将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }

        return sb.toString();
    }

    /*
     * 将16进制数字解码成字符串,适用于所有字符（包括中文）
     */
    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
//将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2) {
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
        }
        return new String(baos.toByteArray());
    }

    public static boolean isEmpty(String msg) {

        if (msg == null || msg.isEmpty()) {
            return true;
        }

        return false;
    }

    /**
     * 字符串截取
     *
     * @param s
     * @param start
     * @param length
     * @return
     */
    public static String subString(String s, int start, int length) {


        try {

            StringBuilder sb = new StringBuilder(s);

            if (sb.length() >= start + length) {
                return sb.substring(start, start + length);
            }

        } catch (Exception ex) {

        }

        return "";

    }


    public static String subString(String s, int start) {


        try {

            StringBuilder sb = new StringBuilder(s);

            if (sb.length() >= start) {
                return sb.substring(start);
            }

        } catch (Exception ex) {

        }

        return "";

    }


    /**
     * base64转16进制
     *
     * @param base64Str base64
     * @return String
     */
    public static String base64ToHexString(String base64Str) {

        try {

            if (Strings.isNullOrEmpty(base64Str)) {
                throw new IllegalArgumentException("参数不能为空");
            }


            byte[] bytes = BaseEncoding.base64().decode(base64Str);

            if (bytes.length <= 0) {
                throw new IllegalArgumentException("Base64解析失败");
            }


            StringBuilder sb = new StringBuilder();

            for (byte b : bytes) {

                String hex = Integer.toHexString(b & 0xFF);

                if (hex.length() == 1) {

                    hex = '0' + hex;

                }

                sb.append(hex.toUpperCase());
            }

            return sb.toString();

        } catch (Exception ex) {
            Logger.e("base64转16进制", ex);
        }

        return null;

    }
}
